package com.jraft;

import com.alipay.sofa.jraft.rhea.LeaderStateListener;
import com.alipay.sofa.jraft.rhea.client.DefaultRheaKVStore;
import com.alipay.sofa.jraft.rhea.client.RheaKVStore;
import com.alipay.sofa.jraft.rhea.options.PlacementDriverOptions;
import com.alipay.sofa.jraft.rhea.options.RheaKVStoreOptions;
import com.alipay.sofa.jraft.rhea.options.StoreEngineOptions;
import com.alipay.sofa.jraft.rhea.options.configured.MemoryDBOptionsConfigured;
import com.alipay.sofa.jraft.rhea.options.configured.PlacementDriverOptionsConfigured;
import com.alipay.sofa.jraft.rhea.options.configured.RheaKVStoreOptionsConfigured;
import com.alipay.sofa.jraft.rhea.options.configured.StoreEngineOptionsConfigured;
import com.alipay.sofa.jraft.rhea.storage.StorageType;
import com.alipay.sofa.jraft.util.Endpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicLong;

public class Node4 {

    final static private AtomicLong leaderTerm=new AtomicLong(-1);
    static Logger logger= LoggerFactory.getLogger(Node4.class);

    public static void main(String[] args) {
        String ip="127.0.0.1";
        int port=8894;

        String dataPath="d:/server/node4/";

        String serverList="127.0.0.1:8891,127.0.0.1:8892,127.0.0.1:8893" +
                ",127.0.0.1:8894,127.0.0.1:8895";


        final StoreEngineOptions engineOptions= StoreEngineOptionsConfigured.newConfigured()
                .withStorageType(StorageType.Memory)
                .withMemoryDBOptions(MemoryDBOptionsConfigured.newConfigured().config())
                .withRaftDataPath(dataPath)
                .withServerAddress(new Endpoint(ip,port))
                .config();


        final PlacementDriverOptions driverOptions= PlacementDriverOptionsConfigured.newConfigured()
                .withFake(true)
                .config();

        final RheaKVStoreOptions kvStoreOptions= RheaKVStoreOptionsConfigured.newConfigured()
                .withInitialServerList(serverList)
                .withStoreEngineOptions(engineOptions)
                .withPlacementDriverOptions(driverOptions)
                .config();


        RheaKVStore store=new DefaultRheaKVStore() ;
        store.init(kvStoreOptions);



        store.addLeaderStateListener(-1L, new LeaderStateListener() {
            @Override
            public void onLeaderStart(long l) {

                System.err.println(String.format("this node became a leader node :{}",l));
            }

            @Override
            public void onLeaderStop(long l) {
                    leaderTerm.set(-1);
            }
        });
    }
}
